<template>
    <div class="user-profile-container">
        <el-card shadow="always" class="profile-card">
            <div class="card-header">
                <el-page-header @back="$router.go(-1)" class="page-header">
                    <template #content>
                        <div class="header-content">
                            <h1>个人信息</h1>
                            <div class="subtitle">管理您的个人资料和账户设置</div>
                        </div>
                    </template>
                </el-page-header>
            </div>

            <el-form ref="profileForm" :model="form" :rules="rules" class="user-form" label-position="top">

                <div class="avatar-card">
<!--                    <div class="info-header">-->
<!--                        <i class="el-icon-picture"></i>-->
<!--                        <span>个人头像</span>-->
<!--                    </div>-->

<!--                    <div class="avatar-content">-->
<!--                        <el-upload-->
<!--                            class="avatar-uploader"-->
<!--                            :action="uploadUrl"-->
<!--                            :show-file-list="false"-->
<!--                            :on-success="handleAvatarSuccess"-->
<!--                            :before-upload="beforeAvatarUpload"-->
<!--                            :headers="uploadHeaders"-->
<!--                            :data="uploadData"-->
<!--                            :on-error="handleUploadError"-->
<!--                        >-->
<!--                            <div class="avatar-preview">-->
<!--                                <img v-if="form.avatar" :src="form.avatar" class="avatar" alt="用户头像">-->
<!--                                <div v-else class="avatar-placeholder">-->
<!--                                    <i class="el-icon-plus avatar-uploader-icon"></i>-->
<!--                                    <div class="tip-text">点击上传头像</div>-->
<!--                                </div>-->
<!--                                <div class="avatar-overlay">-->
<!--                                    <i class="el-icon-camera"></i>-->
<!--                                    <span>更换头像</span>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                        </el-upload>-->

<!--                        <div class="avatar-tips">-->
<!--                            <div class="tip-item">-->
<!--                                <i class="el-icon-info"></i>-->
<!--                                <span>建议尺寸: 200×200</span>-->
<!--                            </div>-->
<!--                            <div class="tip-item">-->
<!--                                <i class="el-icon-info"></i>-->
<!--                                <span>支持 JPG/PNG 格式</span>-->
<!--                            </div>-->
<!--                            <div class="tip-item">-->
<!--                                <i class="el-icon-info"></i>-->
<!--                                <span>大小不超过 2MB</span>-->
<!--                            </div>-->
<!--                        </div>-->
<!--                    </div>-->
                </div>

                <!-- 个人信息卡片 -->
                <div class="info-card">
                    <div class="info-header">
                        <i class="el-icon-user-solid"></i>
                        <span>基本信息</span>
                    </div>

                    <div class="info-grid">
                        <!-- 第一行 -->
                        <div class="info-field">
                            <label>用户名</label>
                            <el-input
                                v-model="form.userName"
                                prefix-icon="user"
                                placeholder="请输入用户名"
                            />
                        </div>

                        <div class="info-field">
                            <label>邮箱</label>
                            <el-input
                                v-model="form.email"
                                prefix-icon="message"
                                placeholder="请输入邮箱"
                            />
                        </div>

                        <!-- 第二行 -->
                        <div class="info-field">
                            <label>真实姓名 <span class="required">*</span></label>
                            <el-input
                                v-model="form.realName"
                                placeholder="请输入真实姓名"
                                clearable
                                prefix-icon="edit"
                            />
                        </div>

                        <div class="info-field">
                            <label>性别</label>
                            <el-select
                                v-model="form.gender"
                                placeholder="请选择性别"
                                @change="handleFieldChange"
                            >
                                <el-option label="男" value="male" />
                                <el-option label="女" value="female" />
                                <el-option label="其他" value="other" />
                            </el-select>
                        </div>

                        <!-- 第三行 -->
                        <div class="info-field">
                            <label>生日</label>
                            <el-date-picker
                                v-model="form.birthday"
                                type="date"
                                placeholder="选择日期"
                                :disabledDate="disabledDate"
                                @change="handleFieldChange"
                                value-format="YYYY-MM-DD"
                            />
                        </div>

                        <div class="info-field">
                            <label>联系电话</label>
                            <el-input
                                v-model="form.phone"
                                placeholder="请输入联系电话"
                                maxlength="11"
                                show-word-limit
                                prefix-icon="phone"
                                @change="handleFieldChange"
                            />
                        </div>

                        <!-- 第四行 -->
                        <div class="info-field full-width">
                            <label>地址</label>
                            <el-input
                                v-model="form.address"
                                type="textarea"
                                :rows="2"
                                placeholder="请输入详细地址"
                                maxlength="100"
                                show-word-limit
                                @change="handleFieldChange"
                            />
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div v-if="hasChanges" class="form-actions">
                    <el-button
                        type="primary"
                        @click="submitForm"
                        :loading="submitting"
                        class="submit-btn"
                    >
                        <i class="el-icon-check"></i> 保存修改
                    </el-button>
                    <el-button @click="resetForm" class="cancel-btn">
                        <i class="el-icon-close"></i> 取消
                    </el-button>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import {getUserInfo, insertUserInfo, updateUserInfo, uploadImage} from '@/api/user'
import { getToken } from '@/utils/auth'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'

dayjs.locale('zh-cn')

export default {
    name: 'UserProfile',
    data() {
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入联系电话'))
            } else if (!/^1[3-9]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号码'))
            } else {
                callback()
            }
        }
      return {
            submitting: false,
            loading: false,
            originalForm: {},
            form: {
                userId: '',
                userName: '',
                email: '',
                realName: '',
                gender: '',
                birthday: '',
                phone: '',
                address: '',
                avatar: ''
            },
            rules: {
                realName: [
                    { required: true, message: '请输入真实姓名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                phone: [
                    { validator: validatePhone, trigger: 'blur' }
                ],
                address: [
                    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
                ]
            },
            uploadUrl: '/api' + '/uploadImage',
            uploadHeaders: {
                'Authorization': 'Bearer ' + getToken()
            },
            uploadData: {
                type: 'avatar'
            },
            Id: 0
        }
    },
    computed: {
        hasChanges() {
            const editableFields = ['userName', 'email', 'realName', 'gender', 'birthday', 'phone', 'address', 'avatar']
            return editableFields.some(field => this.form[field] !== this.originalForm[field])
        }
    },
    async created() {


        this.form.userId=sessionStorage.getItem('userId')
        console.log( this.form.userId)
        await this.fetchUserInfo(this.form.userId)
    },
    methods: {
        async fetchUserInfo(Id) {
            this.loading = true;
            try {
                // 尝试获取用户信息
                const response = await getUserInfo(Id);
                if (response[0].userId==0){
                    await this.insertNewUser(Id);
                }

                // 如果获取成功，填充表单
                if (response && response[0]) {
                    this.form = {
                        userId: response[0]?.userId || Id,  // 确保userId有值
                        userName: response[0]?.user?.userName || '',
                        email: response[0]?.email || '',
                        realName: response[0]?.realName || '',
                        gender: response[0]?.gender || '',
                        birthday: response[0]?.birthday || '',
                        phone: response[0]?.phone || '',
                        address: response[0]?.address || '',
                        avatar: response[0]?.avatar || ''
                    };
                    this.originalForm = JSON.parse(JSON.stringify(this.form));
                } else {
                    // 如果获取成功但数据为空，也视为需要插入新记录
                    await this.insertNewUser(Id);

                }
            } catch (error) {
                // 获取失败时插入新记录
                console.error('获取用户信息失败，尝试创建新用户:', error);
                await this.insertNewUser(Id);
            } finally {
                this.loading = false;
            }
        },

        async insertNewUser(userId) {
            try {
                // 创建默认用户数据
                const newUser = {
                    userId: userId,
                };

                // 执行插入操作
                await insertUserInfo(newUser);

                // 更新表单数据
                this.form = { ...newUser };
                this.originalForm = JSON.parse(JSON.stringify(this.form));

            } catch (insertError) {
                console.error('创建用户失败:', insertError);
                this.$message.error('创建用户记录失败');
                throw insertError; // 可以选择继续抛出错误或处理
            }
            finally {
                // await this.fetchUserInfo(userId)
            }
        },
        handleFieldChange() {
            // 字段变化处理
        },
      disabledDate(time) {
          // console.log('disabledDate 被调用', time);
          return time.getTime() > Date.now()
        },
        resetForm() {
            this.form = JSON.parse(JSON.stringify(this.originalForm))
            this.$message({
                message: '已恢复原始数据',
                type: 'info'
            })
        },
        async submitForm() {
            try {
                this.submitting = true
                await updateUserInfo({
                    userId:this.form.userId,
                    userName: this.form.userName,
                    email: this.form.email,
                    realName: this.form.realName,
                    gender: this.form.gender,
                    birthday: dayjs(this.form.birthday).format('YYYY-MM-DD'),
                    phone: this.form.phone,
                    address: this.form.address,
                    avatar: this.form.avatar
                })
              // console.log(dayjs(this.form.birthday).format('YYYY-MM-DD'))

                    this.$message.success('个人信息更新成功')
                this.originalForm = JSON.parse(JSON.stringify(this.form))
            } catch (error) {
                console.error('更新失败:', error)
                this.$message.error('更新失败: ' + (error.message || '请稍后重试'))
            } finally {
                this.submitting = false
            }
        },
      async customUpload({ file }) {
        try {
          const response = await uploadImage(file, 'avatar')
          this.handleAvatarSuccess(response.data) // 统一处理响应
        } catch (error) {
          this.handleUploadError(error)
        }
      },

      // 成功回调（适配您的响应结构）
      handleAvatarSuccess(response) {
        if (response.code === 200 || response.success) { // 兼容两种成功状态
          this.form.avatar = response.data?.url || response.url
          this.$message.success(response.message || '头像上传成功')
          this.$emit('upload-success', this.form.avatar) // 可选：触发事件
        } else {
          this.$message.error(response.message || '头像上传失败')
        }
      },

      // 上传前校验（保持原有逻辑）
      beforeAvatarUpload(file) {
        const validTypes = ['image/jpeg', 'image/png', 'image/jpg']
        const isImage = validTypes.includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isImage) {
          this.$message.error('只能上传 JPG/PNG 格式的图片!')
          return false
        }
        if (!isLt2M) {
          this.$message.error('图片大小不能超过 2MB!')
          return false
        }
        return true
      },

      // 错误处理（增强版）
      handleUploadError(err) {
        console.error('上传错误详情:', err)
        let message = '头像上传失败'

        if (err.response) {
          // 处理HTTP错误响应
          const data = err.response.data
          message = data.message ||
              (data.error || '服务器错误：' + err.response.status)
        } else if (err.request) {
          message = '网络错误，请检查连接'
        } else if (err.message) {
          message = err.message
        }

        this.$message.error(message)
        this.$emit('upload-error', err) // 可选：触发错误事件
      }

    }
}
</script>

<style scoped lang="scss">
/* 样式部分保持不变，与之前相同 */
.user-profile-container {
    padding: 24px;
    max-width: 900px;
    margin: 0 auto;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    min-height: calc(100vh - 48px);

    .profile-card {
        border-radius: 16px;
        border: none;
        box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
        overflow: hidden;
        transition: all 0.3s ease;

        &:hover {
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
        }
    }

    .page-header {
        padding: 24px;
        background: linear-gradient(135deg, #6C63FF 0%, #4A42D6 100%);
        color: white;
        margin-bottom: 0;

        ::v-deep .el-page-header__content {
            .header-content {
                h1 {
                    font-size: 24px;
                    font-weight: 600;
                    margin: 0;
                    color: white;
                    letter-spacing: 0.5px;
                }

                .subtitle {
                    font-size: 14px;
                    opacity: 0.9;
                    margin-top: 6px;
                    font-weight: 400;
                    color: rgba(255, 255, 255, 0.85);
                }
            }

            .el-page-header__left {
                color: white;
                .el-icon-back {
                    font-size: 18px;
                }
            }
        }
    }

    .user-form {
        padding: 24px;
        background-color: #fff;

        .info-card, .avatar-card {
            background: #fff;
            border-radius: 12px;
            margin-bottom: 24px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            border: 1px solid #f0f0f0;
            overflow: hidden;
        }

        .info-header {
            padding: 16px 24px;
            background: linear-gradient(90deg, rgba(108, 99, 255, 0.1) 0%, rgba(108, 99, 255, 0.05) 100%);
            border-bottom: 1px solid #f5f5f5;
            display: flex;
            align-items: center;
            font-size: 16px;
            font-weight: 500;
            color: #333;

            i {
                color: #6C63FF;
                margin-right: 10px;
                font-size: 18px;
            }
        }

        .info-grid {
            padding: 16px 24px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;

            .info-field {
                label {
                    display: block;
                    margin-bottom: 8px;
                    font-size: 14px;
                    color: #555;
                    font-weight: 500;

                    .required {
                        color: #ff4d4f;
                        margin-left: 4px;
                    }
                }

                &.full-width {
                    grid-column: span 2;
                }
            }
        }

        .avatar-card {
            .avatar-content {
                padding: 24px;
                display: flex;
                align-items: flex-start;
                gap: 40px;

                @media (max-width: 768px) {
                    flex-direction: column;
                    gap: 20px;
                }
            }

            .avatar-uploader {
                .avatar-preview {
                    width: 160px;
                    height: 160px;
                    border-radius: 12px;
                    overflow: hidden;
                    border: 1px dashed #dcdfe6;
                    transition: all 0.3s ease;
                    position: relative;
                    background-color: #f9f9f9;

                    &:hover {
                        border-color: #6C63FF;

                        .avatar-overlay {
                            opacity: 1;
                        }
                    }

                    .avatar {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }

                    .avatar-placeholder {
                        width: 100%;
                        height: 100%;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        color: #999;

                        .avatar-uploader-icon {
                            font-size: 32px;
                            margin-bottom: 8px;
                            color: #c0c4cc;
                        }

                        .tip-text {
                            font-size: 14px;
                        }
                    }

                    .avatar-overlay {
                        position: absolute;
                        top: 0;
                        left: 0;
                        right: 0;
                        bottom: 0;
                        background: rgba(0, 0, 0, 0.5);
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        color: white;
                        opacity: 0;
                        transition: opacity 0.3s ease;

                        i {
                            font-size: 24px;
                            margin-bottom: 8px;
                        }

                        span {
                            font-size: 14px;
                        }
                    }
                }
            }

            .avatar-tips {
                flex: 1;
                display: flex;
                flex-direction: column;
                gap: 12px;

                .tip-item {
                    display: flex;
                    align-items: center;
                    font-size: 14px;
                    color: #666;

                    i {
                        color: #6C63FF;
                        margin-right: 8px;
                        font-size: 16px;
                    }
                }
            }
        }

        .form-actions {
            margin-top: 32px;
            display: flex;
            justify-content: flex-end;
            gap: 16px;

            .submit-btn {
                padding: 10px 24px;
                border-radius: 8px;
                font-weight: 500;
                letter-spacing: 0.5px;
                transition: all 0.3s ease;
                background: linear-gradient(135deg, #6C63FF 0%, #4A42D6 100%);
                border: none;

                &:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 12px rgba(108, 99, 255, 0.3);
                }

                &:active {
                    transform: translateY(0);
                }
            }

            .cancel-btn {
                padding: 10px 24px;
                border-radius: 8px;
                font-weight: 500;
                letter-spacing: 0.5px;
                transition: all 0.3s ease;
                background: white;
                border: 1px solid #e0e0e0;
                color: #555;

                &:hover {
                    background: #f5f5f5;
                    border-color: #c0c0c0;
                }
            }
        }
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .user-profile-container {
        padding: 16px;

        .profile-card {
            border-radius: 12px;
        }

        .user-form {
            padding: 16px;

            .info-grid {
                grid-template-columns: 1fr;

                .info-field.full-width {
                    grid-column: span 1;
                }
            }

            .form-actions {
                flex-direction: column;

                button {
                    width: 100%;
                }
            }
        }
    }
}
</style>